package com.example.liuhb.h5;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.liuhb.NOME.ErrorResult;
import com.example.liuhb.NOME.GetOrdersPrams;
import com.example.liuhb.NOME.GetOrdersResult;
import com.example.liuhb.NOME.GetOrdersResultDate;
import com.example.liuhb.NOME.Prams;
import com.example.liuhb.NOME.Result;
import com.example.liuhb.NOME.ResultCallOrder;
import com.example.liuhb.NOME.ResultData;
import com.example.liuhb.R;
import com.example.liuhb.databinding.WelcomeBinding;
import com.example.liuhb.rxjava.RxjavaDemoActivity;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Path;

/**
 * Created by liu.hb on 2018/6/22.
 */

public class WelcomeActivity extends Activity implements View.OnClickListener {
    WelcomeBinding b;
    String accessToken;
    static int a;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.welcome);
        b = DataBindingUtil.setContentView(this, R.layout.welcome);
        accessToken="";
        iniPower();
    }
    public void btnSendReq(View v) {
        b.responText.setText("");
        sendReqWithHttpURLConnection();
    }

    public void btnSendOkReq(View v) {
        b.responText.setText("");
        sendReqWithHttpOkHttp();
    }
    void  iniPower(){
        //动态获取新权限只需加到下方数组中即可
        String[] permissions = new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CAMERA};
        List<String> permissionsList = new ArrayList<String>();
        for (int i = 0; i < permissions.length; i++){
            if (ActivityCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                permissionsList.add(permissions[i]);
            }
            if(permissions.length>0){
                ActivityCompat.requestPermissions(WelcomeActivity.this, permissions, 2);
            }
        }

        if(ContextCompat.checkSelfPermission(WelcomeActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(WelcomeActivity.this,new  String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 4);
        }else{
            //updateVersion(msg);
        }
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED){ //表示未授权时
            //进行授权
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.BLUETOOTH_ADMIN},2);
        }else{


        }
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED){ //表示未授权时
            //进行授权
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CALL_PHONE},3);
        }else{
            //调用打电话的方法

        }

        if(ContextCompat.checkSelfPermission(WelcomeActivity.this, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(WelcomeActivity.this,new  String[] {Manifest.permission.CAMERA}, 5);
        }else{
            //updateVersion(msg);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 5:
                if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(WelcomeActivity.this,"权限获取成功，请再次操作",Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(WelcomeActivity.this,"无读写SD卡权限",Toast.LENGTH_SHORT).show();
                }
        }
    }
    public void btnNOME(View v){
        Prams prams = new Prams();
        prams.userNameOrEmailAddress ="admin2";
        prams.password ="qweqwe";
        prams.rememberClient =true;
        String BASE_URL = "http://192.168.100.23:21021/"; //这里必须是BaseURL，只能到端口
        Retrofit retrofit=initRetrofit(BASE_URL);
        TaskGetTableServer server = retrofit.create(TaskGetTableServer.class);
        //创建网络请求
//        Call<Result> call = server.getResult(prams);
//        System.out.println("call:"+call.request().toString());
//        new ResultCall(this, call) {
//            @Override
//            public void onSuccess(Result obj) {
//          System.out.println("-----------obj.success:"+obj.success);
//                if(obj!=null&&obj.success){
//                    toast("获取token成功\n accessToken:"+obj.result.accessToken);
//                    accessToken="bearer  "+obj.result.accessToken;
//                    System.out.println("accessToken:"+accessToken);
//                }else{
//                    if(obj.error!=null){
//                        System.out.println("obj.error:"+obj.error);
//                        toast("错误代码："+obj.error.code+"\n错误信息："+obj.error.message);
//                    }
//
//                }
//            }
//        };
    }
    public void btnOrder(View v){
        if (accessToken.equalsIgnoreCase("")) {
            //没有Token先获取在查询单号
            GetToken();

        }else{
            //有Token直接查询单号
            GetBillNo();
        }
    }
    public void GetToken(){
        Prams prams1 = new Prams();
        prams1.userNameOrEmailAddress ="admin2";
        prams1.password ="qweqwe";
        prams1.rememberClient =true;
        String BASE_URL1= "http://192.168.100.23:21021/"; //这里必须是BaseURL，只能到端口
        Retrofit retrofit1=initRetrofit(BASE_URL1);
        TaskGetTableServer server1 = retrofit1.create(TaskGetTableServer.class);
        //创建网络请求
        Call<Result<ResultData>> call1 = server1.getResult(prams1);
        System.out.println("call:"+call1.request().toString());
        new ResultCall(WelcomeActivity.this, call1) {
            @Override
            public void onSuccess(Result obj) {
                System.out.println("-----------obj.success:"+obj.success);
                if(obj!=null&&obj.success){
                    if(obj.result!=null){
                        ResultData data= (ResultData) obj.result;
                        toast("获取token成功\n accessToken:"+data.accessToken);
                        accessToken="Bearer  "+data.accessToken;
                        System.out.println("accessToken:"+accessToken);
                        GetBillNo();
                    }
                }else{
                    if(obj.error!=null){
                        System.out.println("obj.error:"+obj.error);
                        toast("错误代码："+obj.error.code+"\n错误信息："+obj.error.message);
                    }
                }
            }

//            @Override
//            public void onSuccess(Result<ResultData> obj) {
//                System.out.println("-----------obj.success:"+obj.success);
//                if(obj!=null&&obj.success){
//                    toast("获取token成功\n accessToken:"+obj.result.accessToken);
//                    accessToken="bearer  "+obj.result.accessToken;
//                    System.out.println("accessToken:"+accessToken);
//                    GetBillNo();
//                }else{
//                    if(obj.error!=null){
//                        System.out.println("obj.error:"+obj.error);
//                        toast("错误代码："+obj.error.code+"\n错误信息："+obj.error.message);
//                    }
//
//                }
//            }
        };
    }
    public void GetBillNo(){
        GetOrdersPrams prams = new GetOrdersPrams();
        prams.Billion ="string";
        String BASE_URL = "http://192.168.100.23:21021/"; //这里必须是BaseURL，只能到端口
        String URL="http://192.168.100.23:21021/api/services/app/OrdersMaster/GetOrdersMasterByBillnoAsync";
        Retrofit retrofit=initRetrofit(BASE_URL);
        TaskGetTableServer server = retrofit.create(TaskGetTableServer.class);
        //创建网络请求"20180714145429542937"
        Call<Result<GetOrdersResultDate>> call = server.getOrderResult(URL,"20180714145429542937");
        System.out.println("call:"+call.request().toString());
        new ResultCall(WelcomeActivity.this, call) {
            @Override
            public void onSuccess(Result obj) {
                System.out.println("-----------obj.success:"+obj.success);
                if(obj!=null&&obj.success){
                    if(obj.result!=null){
                        GetOrdersResultDate data= (GetOrdersResultDate) obj.result;
                        System.out.println("data.creationTime:"+data.creationTime);
                    }
                }else{
                    if(obj.error!=null){
                        System.out.println("obj.error:"+obj.error);
                        toast("错误代码："+obj.error.code+"\n错误信息："+obj.error.message);
                    }else{
                        System.out.println("obj.error:");
                        toast("获取单号失败！");
                    }
                }
            }
//
//            @Override
//            public void onSuccess(GetOrdersResult obj) {
//                if(obj!=null&&obj.success){
//                    if(obj.result!=null){
//                        System.out.println("creationTime:"+obj.result.creationTime);
//                    }
//                }else{
//                    if(obj.error!=null){
//                        System.out.println("obj.error:"+obj.error);
//                        toast("错误代码："+obj.error.code+"\n错误信息："+obj.error.message);
//                    }
//
//                }
//            }
        };
    }
    public void btnSendRetrofit(View v) {
        b.responText.setText("");
        sendRetrofit();
    }
    public void btnRxjavaDemo(View v){
        Intent i=new Intent(this, RxjavaDemoActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(i);
    }
    private void sendRetrofit() {
        ResultDemo result = new ResultDemo();
        result.CompanyID = "100";
        result.UserID = "HK00001246";
        result.APIKey = "android_dbs";
        result.SessionKey = "14A30225B2524C196DD595EAAB73D864";
        result.label = "User_UserLoginNoCompanyID";
        result.list = new String[]{"100801","1","LoginNoCom","android_dbs","869775012152663","http://192.168.8.35:80","BDS","1.64",""};
        String BASE_URL = "http://192.168.8.35:80/"; //这里必须是BaseURL，只能到端口
        Retrofit retrofit=initRetrofit(BASE_URL);
        TaskGetTableServer server = retrofit.create(TaskGetTableServer.class);
        //创建网络请求
        Call<TableModel> call = server.get(result);

//        new ResultCall(this, call) {
//            @Override
//            public void onSuccess(TableModel obj) {
//                System.out.println("-----------obj.IsOK:"+obj.IsOK);
//                System.out.println("-----------obj.Msg:"+obj.Msg);
//                System.out.println("-----------obj.list:"+obj.list0[1][2].toString());
//                //System.out.println("-----------obj.MsgList:"+obj.list.get(0));
//            }
//        };

    }
    public Retrofit initRetrofit(String BASE_URL) {
        //OkHttp日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i("okhttp:-->", message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //Header拦截器
        Interceptor headerInterceptor = new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();

                Request request = original.newBuilder()
                        .header("Accept", "application/json")
                        .header("Content-Type", "application/json; charset=UTF-8")
                        .header("Authorization",accessToken)
                        .method(original.method(), original.body())
                        .build();

                return chain.proceed(request);
            }
        };

        //HttpClient
        OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
        httpBuilder.addInterceptor(headerInterceptor);
        httpBuilder.addInterceptor(loggingInterceptor);
        OkHttpClient client = httpBuilder.build();

//        BASE_URL = "http://192.168.8.35:80/"; //这里必须是BaseURL，只能到端口
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return  retrofit;
    }
    public void btnCAMERA(View v) {
        b.responText.setText("");
//        new IntentIntegrator(WelcomeActivity.this).initiateScan(); //初始化扫描
        IntentIntegrator integrator = new IntentIntegrator(WelcomeActivity.this);
        // 设置要扫描的条码类型，ONE_D_CODE_TYPES：一维码，QR_CODE_TYPES-二维码
        integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
        integrator.setCaptureActivity(ScanActivity.class);
        integrator.setPrompt("请扫描"); //底部的提示文字，设为""可以置空
        integrator.setCameraId(0); //前置或者后置摄像头
        integrator.setBeepEnabled(false); //扫描成功的「哔哔」声，默认开启
        integrator.setBarcodeImageEnabled(true);
        integrator.initiateScan();
//        sendReqWithRetrofit();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if(result.getContents() == null) {
                Toast.makeText(this, "扫码取消！", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "扫描成功，条码值: " + result.getContents(), Toast.LENGTH_LONG).show();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 注1： Retrofit2 的baseUlr 必须以 /（斜线） 结束，不然会抛出一个IllegalArgumentException,
     * 所以如果你看到别的教程没有以 / 结束，那么多半是直接从Retrofit 1.X 照搬过来的。
     * 注2： 上面的 注1 应该描述为 baseUrl 中的路径(path)必须以 / 结束，
     * 因为有些特殊情况可以不以/结尾，
     * 比如 其实这个 URL https://www.baidu.com?key=value用来作为baseUrl其实是可行的，
     * 因为这个URL隐含的路径就是 /（斜线，代表根目录） ，
     * 而后面的?key=value在拼装请求时会被丢掉所以写上也没用。
     * 之所以 Retrofit 2 在文档上要求必须以 /（斜线） 结尾的要求想必是要消除歧义以及简化规则。
     */
    private void sendReqWithRetrofit() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.8.35:80/")
                .build();
        BlogService service = retrofit.create(BlogService.class);
        Call<ResponseBody> call = service.getBlog(2);
        // 用法和OkHttp的call如出一辙,
        // 不同的是如果是Android系统回调方法执行在主线程
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                try {
                    System.out.println(response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
            }
        });

    }

    public interface BlogService {
        @GET("blog/{id}")
        Call<ResponseBody> getBlog(@Path("id") int id);
    }

    private void sendReqWithHttpOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request req = new Request.Builder().url("https://www.baidu.com").build();
                    Response response = client.newCall(req).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }

            }
        }).start();
    }

    @Override
    public void onClick(View view) {

    }

    public void sendReqWithHttpURLConnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("https://www.baidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    //下面对获取到的输入流进行读取
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    showResponse(response.toString());
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }

            }
        }).start();
    }

    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                b.responText.setText(response);
            }
        });
    }
}
